package org.vectrics.user.client;


import java.awt.*;
import java.awt.event.*;
import java.util.Collection;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import org.apache.log4j.Logger;
import org.vectrics.VectricsException;
import org.vectrics.user.Person;
import org.vectrics.user.ContactInfo;
import org.vectrics.user.UserSummary;
import org.vectrics.user.PersonSynch;
import org.vectrics.location.*;
import org.vectrics.swing.GuiManager;
import org.vectrics.swing.Row;
import org.vectrics.swing.Cell;
import org.vectrics.client.framework.ErrorFrame;
import org.vectrics.client.module.*;
import org.vectrics.swing.TablePanel;


//	mainSplitPane
//		TOP
//			messageScrollPane
//				listAndSearchPanel
//		BOTTOM
//			detailPanel
//				detailFIeldsPanel
//				

public class UserManagerFrame extends ModulePanel implements ListSelectionListener {
    private transient static Logger log = Logger.getLogger(UserManagerFrame.class);
    
    UserTableModel tableModel = new UserTableModel();
    JSplitPane mainSplitPane = new JSplitPane();
    JPanel listAndSearchPanel = new JPanel();
    TablePanel detailFieldsTable = new TablePanel();
    JPanel detailPanel = new JPanel();
	JPanel bottomPanel = new JPanel();
	JPanel detailOptionsPanel = new JPanel();
	JPanel searchPanel = new JPanel();
    JTable userTable = new JTable(tableModel);
    FlowLayout paneLayout2 = new FlowLayout();
    JScrollPane messageScrollPane = new JScrollPane();
    JLabel lastNameLabel = new JLabel();
    JPanel messageListPanel = new JPanel();
    JPanel blankPanel = new JPanel();
	Dimension detailTextMinSize = new Dimension(80, 18);
	JLabel firstNameText = null;
	JLabel middleNameText = null;
	JLabel lastNameText = null;
	JLabel userNameText = null;
	JLabel homeAddressText = null;
	JLabel homeCityStateZipText = null;
	JLabel homePhone = null;
	JTextField editSearchFirstName = new JTextField();
	JTextField editSearchLastName = new JTextField();
	private static Color FIELD_COLOR = new Color(230, 230, 240);
	private PersonSynch selectedUserSynch = null;
	private int detailFieldCount = 0;
	
		
    public UserManagerFrame()  {
    	super();
        log.debug("Message Frame Constructor");
        try {
            init();
        }
        catch(Exception e) {
            log.error("Exception in MessageFrame constructor", e);
        }
    }
    
    private void init() throws Exception {
        log.info("init() - method to display controls on this frame");
		this.setBackground(Color.RED); 
		this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));       
		this.setFont(GuiManager.getInstance().getStandardFont());
		//this.setLayout(new BorderLayout());
		this.add(mainSplitPane);

		this.add(this.mainSplitPane, null);
		mainSplitPane.setDividerSize(10);
		mainSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		//mainSplitPane.setLayout(new BorderLayout());
		

		searchPanel.setBorder(BorderFactory.createEtchedBorder());
		initSearchPanelComponents(searchPanel);

		messageScrollPane.setFont(GuiManager.getInstance().getStandardFont());
		messageScrollPane.setBorder(BorderFactory.createEtchedBorder());
		messageScrollPane.setToolTipText("");
		
		this.listAndSearchPanel.setLayout(new BoxLayout(listAndSearchPanel, BoxLayout.Y_AXIS));
		this.listAndSearchPanel.add(searchPanel);
		this.listAndSearchPanel.add(messageScrollPane);
		
        detailFieldsTable.setBorder(BorderFactory.createEtchedBorder());
        detailFieldsTable.setPreferredSize(new Dimension(300, 100));
        detailFieldsTable.setMaximumSize(new Dimension(300, 300));

        userTable.setFont(GuiManager.getInstance().getStandardFont());
        userTable.setAutoscrolls(false);
        userTable.setRowHeight(14);

        messageListPanel.setLayout(paneLayout2);
        messageListPanel.setMinimumSize(new Dimension(146, 300));
        messageListPanel.setPreferredSize(new Dimension(454, 490));


        messageScrollPane.getViewport().add(userTable, null);
        userTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        userTable.getSelectionModel().addListSelectionListener(this);

		mainSplitPane.add(listAndSearchPanel, JSplitPane.TOP);
		mainSplitPane.add(bottomPanel, JSplitPane.BOTTOM);
		bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
		bottomPanel.add(detailPanel);
        
        buildUserDetailsDisplay();
   }


	private JLabel makeDetailRow(TablePanel panel, int rowNumber, String caption) {
		Row row = panel.addRow();
		
		int rowHeight = 22;
		int leftInset = 4;
		int topInset = 4;
		
		int labelX = 0 + leftInset;
		int labelWidth = 100;
		int labelHeight = 18;
		
		int valueX = labelX + labelWidth + 10 + leftInset;
		int valueY = (rowNumber * 22) + topInset;
		int valueWidth = 120;
		int valueHeight = 18;
		
		JLabel label = new JLabel(); 
		label.setText(caption);
		label.setFont(GuiManager.getInstance().getStandardFont());
		label.setBounds(labelX, valueY, labelWidth, labelHeight);
		Cell labelCell = row.addCell(label);
	
		JLabel fieldText = new JLabel();
		fieldText.setFont(GuiManager.getInstance().getStandardFont());
		fieldText.setBackground(FIELD_COLOR);
		fieldText.setBorder(BorderFactory.createEtchedBorder());
		fieldText.setBounds(valueX, valueY, valueWidth, valueHeight);
		Cell fieldCell = row.addCell(fieldText);
			
		return(fieldText);
	}

	private void buildUserDetailsDisplay() {
		//TableBuilder detailBuilder = new TableBuilder();		
		JButton moreDetailsButton = GuiManager.getInstance().createButton("More Details", 90, 20);
		moreDetailsButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(ActionEvent e) {
					moreDetailsButtonActionPerformed(e);
				}
			});
		
		
		JButton editDetailsButton = GuiManager.getInstance().createButton("Edit", 90, 20);
		editDetailsButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(ActionEvent e) {
					editUserButtonActionPerformed(e);
				}
			});
		
				
		detailOptionsPanel.setLayout(new BoxLayout(detailOptionsPanel, BoxLayout.Y_AXIS));
		detailOptionsPanel.add(moreDetailsButton);
		detailOptionsPanel.add(editDetailsButton);

		
		
		log.debug("creating first details grid");
		
		firstNameText = makeDetailRow(this.detailFieldsTable, 0, "First Name");
		lastNameText = makeDetailRow(this.detailFieldsTable, 1, "Last Name");
		middleNameText = makeDetailRow(this.detailFieldsTable, 2, "Middle Name");
		userNameText = makeDetailRow(this.detailFieldsTable, 3, "User Name");
		homeAddressText = makeDetailRow(this.detailFieldsTable, 4, "Home Address");
		homeCityStateZipText = makeDetailRow(this.detailFieldsTable, 5,  "City, State, Zip");
		homePhone = makeDetailRow(this.detailFieldsTable, 6, "Home Phone");

		
		JTabbedPane detailTabbedPane = GuiManager.getInstance().createTabbedPane();
		detailTabbedPane.addTab("User Details", detailFieldsTable);
		detailTabbedPane.addTab("Other Details", new JPanel());
		

		detailPanel.setLayout(new BorderLayout());
		detailPanel.setMinimumSize(new Dimension(100, 80));
		detailPanel.add(detailTabbedPane, BorderLayout.CENTER);
		detailPanel.add(detailOptionsPanel, BorderLayout.EAST);
	   	
		clearEventDetailDisplay();
	   	
	   	this.validate();
	}
	
	

    // Detect user selection changes with Message table.
    public void valueChanged(ListSelectionEvent iEvent)
    {
        log.debug("valueChanged() - method to detect user selection changes with message table.");
        ListSelectionModel selModel = (ListSelectionModel)iEvent.getSource();
        if (selModel.isSelectionEmpty()) {
            clearEventDetailDisplay();
        }
        else {
            int selIndex = selModel.getMinSelectionIndex();
            //System.out.println("Selected index = " + selIndex);
            
            PersonSynch userSynch = tableModel.getElementAt(selIndex);
            displayEventDetails(userSynch);
        };
    };

	private void initSearchPanelComponents(JPanel searchPanel) {
		log.debug("initSearchPanelComponents() - creating search edit boxes inside horiz sub panels");
		int searchPanelHeight = 25;
		
		searchPanel.setLayout(null);
		searchPanel.setMinimumSize(new Dimension(100, searchPanelHeight));
		searchPanel.setMaximumSize(new Dimension(4000, searchPanelHeight));
		searchPanel.setPreferredSize(new Dimension(300, searchPanelHeight));
		
		
		
		JLabel lastNameSearchLabel = new JLabel();
		lastNameSearchLabel.setFont(GuiManager.getInstance().getStandardFont());
		lastNameSearchLabel.setText("Last Name");
		int x = 10;
		int y = 2;
		int hSpace = 8;
		lastNameSearchLabel.setBounds(x, y, 60, 18);
		x += lastNameSearchLabel.getSize().width;
		x += hSpace;
		searchPanel.add(lastNameSearchLabel);
		editSearchLastName.setText("");
		editSearchLastName.setBounds(x, y, 140, 18);
		x += editSearchLastName.getSize().width;
		x += 2 * hSpace;
		searchPanel.add(editSearchLastName);		
		
		JLabel firstNameSearchLabel = new JLabel();
		firstNameSearchLabel.setText("First Name");
		firstNameSearchLabel.setFont(GuiManager.getInstance().getStandardFont());
		firstNameSearchLabel.setBounds(x, y, 60, 18);
		x += lastNameSearchLabel.getSize().width;
		x += hSpace;
		searchPanel.add(firstNameSearchLabel);

		editSearchFirstName.setText("");
		editSearchFirstName.setBounds(x, y, 140, 18);
		x += editSearchFirstName.getSize().width;
		x += hSpace * 2;
		searchPanel.add(editSearchFirstName);		

		JButton searchButton = GuiManager.getInstance().createButton("Search", 90, 20);
		Dimension size = searchButton.getPreferredSize();
		searchButton.setBounds(x, y, size.width, size.height);
		searchButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(ActionEvent e) {
					searchButtonActionPerformed(e);
				}
			});
		searchPanel.add(searchButton);
	}


    private void clearEventDetailDisplay()
    {
        userNameText.setText(" ");
        firstNameText.setText(" ");
        middleNameText.setText(" ");
        lastNameText.setText(" ");
		homeAddressText.setText(" ");
		homeCityStateZipText.setText(" ");
		homePhone.setText(" ");
    };


	

    private void displayEventDetails(PersonSynch userSynch) {
    	
        if (userSynch != null) {
        	clearEventDetailDisplay();
        	selectedUserSynch = userSynch;
			Person user = selectedUserSynch.getPerson();
			if (user != null) {
	            userNameText.setText(user.getUser().getUserName());
	            firstNameText.setText(user.getFirstName());
	            lastNameText.setText(user.getLastName());
	            
				
				ContactInfo contactInfo = user.getContactInfo(); 
				if (user.getContactInfo() != null) {			
					//homeAddressText.setText(null);
					Address homeAddress = user.getContactInfo().getHomeAddress();
					if (homeAddress != null) {
						homeAddressText.setText(user.getContactInfo().getHomeAddress().getAddress1());
						homeCityStateZipText.setText("");
					}
					if (contactInfo.getHomePhone() != null)
						homePhone.setText(contactInfo.getHomePhone().getFormattedNumber());
				}
				
            }
			else {
				UserSummary userSummary = selectedUserSynch.getUserSummary();
				if (userSummary != null) {
		            userNameText.setText(userSummary.getUserName());
		            firstNameText.setText(userSummary.getFirstName());
	    	        lastNameText.setText(userSummary.getLastName());
	    	        middleNameText.setText(userSummary.getMiddleName());
				}
				enableDetailOptions();
			}
        } 
        else {
			log.debug("displayEventDetails() - clearing field display");
			selectedUserSynch = null;
			//clearEventDetailDisplay();
        	disableDetailOptions();
        }
        bottomPanel.doLayout();
		
		firstNameText.validate();
		userNameText.validate();
		detailFieldsTable.validate();
		this.repaint();
		this.validateTree();
    }


	private void enableDetailOptions() {
	}

	private void disableDetailOptions() {
		
	}


	/**
	 * Search button clicked, get users which match criteria.
	 */
	protected void searchButtonActionPerformed(ActionEvent e) {
		try {
			log.info("searchButtonActionPerformed() - Ok button pressed");
			UserDataManager userMgr = UserDataManager.getInstance();
			String firstName = this.editSearchFirstName.getText();
			String lastName = this.editSearchLastName.getText(); 
			Collection userListProps = userMgr.getUserHoldersWithNameMatch(firstName, lastName);            
			this.tableModel.setUserHolderList(userListProps);
			log.info("searchButtonActionPerformed() - New server connection created");
		}
		catch (Exception ex) {
			log.error("Exception searching after button pressed: ", ex);
		};
	}

	/**
	 * Search button clicked, get users which match criteria.
	 */
	protected void moreDetailsButtonActionPerformed(ActionEvent e) {
		try {
			log.debug("details button pressed");
			UserDataManager userMgr = UserDataManager.getInstance();
			userMgr.getUserDetails(selectedUserSynch);
			displayEventDetails(selectedUserSynch);
		}
		catch (Exception ex) {
			log.error("Exception searching after button pressed: ", ex);
		};
	}

	protected void editUserButtonActionPerformed(ActionEvent e) {
		editSelectedUser();
	}

	private void editSelectedUser() {
		//UserEditFrame form = new UserEditFrame();
		Class moduleClass = UserEditModule.class;
		try {
			UserEditModule module = (UserEditModule)this.findModule(moduleClass);
			module.editUser(selectedUserSynch);
		}
		catch (VectricsException ve) {
			log.error("Error setting up user edit", ve);
			ErrorFrame.showError("Error setting up user edit", "Error setting up user edit.", ve.getMessage());
		}
		
	}
        

}